package cn.nubia.admin.common.freemaker;

import cn.nubia.admin.common.springmvc.WebContext;
import freemarker.core.Environment;
import freemarker.template.*;
import freemarker.template.utility.StringUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * Created by justin on 15/7/31.
 */
public class PermissionDirective implements TemplateDirectiveModel {
    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {

        Object paramValue = StringUtils.trim(getParam(map, "value",""));

        if(paramValue==null || "".equals(paramValue.toString()))templateDirectiveBody.render(environment.getOut());

        Map<String,Boolean> permissionMap = WebContext.getPermission();

        if(permissionMap.containsKey(paramValue.toString())){
            templateDirectiveBody.render(environment.getOut());
        }
    }

    static String getRequiredParam(Map params,String key) throws TemplateModelException {
        Object value = params.get(key);
        if(value == null || StringUtils.isEmpty(value.toString())){
            throw new TemplateModelException("not found required parameter: "+key +" for PERMISSION directive");
        }
        return value.toString();
    }

    static String getParam(Map params,String key,String defaultValue){
        Object value = params.get(key);
        return value == null ? defaultValue:value.toString();
    }
}
